import './ripple.less'

const ripple = {}

ripple.install = (Vue, option = {}) => {
  const config = Object.assign(defaultConfig, option)
  Vue.directive('ripple', {
    bind(el) {
      el.addEventListener('click', e => {
        el.style.position = 'relative'
        
        if (config.overflow === 'hidden') {
          el.style.overflow = 'hidden'
        }

        let ripple = el.querySelector('.ripple')
        if (!ripple) {
          ripple = createRipple(el, config)
          el.appendChild(ripple)
        } else {
          ripple.classList.remove('ripple-animation-3')
          ripple.classList.remove('ripple-animation-1')
        }
        setPosition(el, ripple, config, e)
        setTimeout(() => ripple.classList.add(config.overflow === 'hidden' ? 'ripple-animation-3' : 'ripple-animation-1'))
      })
    }
  })
}

const createRipple = (el, config) => {
  const ripple = document.createElement('span')
  const rect = el.getBoundingClientRect()
  const max = Math.max(rect.height, rect.width)
  ripple.style.height = ripple.style.width = `${max}px`
  ripple.style.backgroundColor = config.color
  ripple.className = 'ripple'
  return ripple
}

const setPosition = (el, ripple, config, event) => {
  const rect = el.getBoundingClientRect()
  const max = Math.max(rect.height, rect.width)
  if (config.type === 'center') {
    ripple.style.top = `${rect.height / 2 - max / 2}px`
    ripple.style.left = `${rect.width / 2 - max / 2}px`
  } else {
    const { pageX, pageY } = event
    ripple.style.top = `${pageY - rect.top - max / 2 - document.body.scrollTop}px`
    ripple.style.left = `${pageX - rect.left - max / 2 - document.body.scrollLeft}px`
  }
}

const defaultConfig = {
  color: 'rgba(0, 0, 0, 0.15)',
  type: 'hit',
  overflow: 'hidden'
  // overflow: 'none'
}

export default ripple
